package com.yayo.mangement.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @desc:
 * @author: yang
 * @date: 2022/9/6
 */
public class FileConverterUtil {
    /**
     * 将文件转换成Base64编码 将文件转化为字节数组字符串，并对其进行Base64编码处理
     *
     * @param path 待处理图片
     * @return
     */
    public static String imageConversionImageBASE64(String path) {

        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }

    /**
     * base64 字符串转Image
     * @param base64
     * @return
     * @throws IOException
     */
    public static BufferedImage BASE64ConversionImage(String base64) throws IOException {
        if (StringUtils.isBlank(base64)) {
            throw new RuntimeException("String cannot be empty!");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        return ImageIO.read(inputStream);
    }

    /**
     * 把Image转base64
     * @param image
     * @return
     * @throws IOException
     */
    public static String imageConversionImageBASE64(BufferedImage image) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        return new BASE64Encoder().encode(stream.toByteArray());
    }

    //base64字符串转化成图片
    public static boolean generateImage(String imgStr,String path)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
}
